package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2022-09-13 15:02 星期二
 * description:
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private AdminRoleDao adminRoleDao;

    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    /**
     * 根据用户id获取角色数据
     * @param adminId
     * @return
     */
    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {

        //查询所有的角色
        List<Role> allRoleList = roleDao.findAll();

        //拥有的角色id
        List<Long> existRoleIdList = adminRoleDao.findRoleIdsByAdminId(adminId);

        //对角色进行分类（已分配角色 和 未分配角色）
        ArrayList<Role> noAssignRoleList = new ArrayList<>();
        ArrayList<Role> assignRoleList = new ArrayList<>();

        //遍历所有的角色
        for (Role role : allRoleList) {
            //若该角色的id存在于existRoleIdList 则表示已分配该权限
            if (existRoleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else{
                noAssignRoleList.add(role);
            }
        }
        Map<String,Object> roleMap = new HashMap();
        roleMap.put("noAssignRoleList",noAssignRoleList);
        roleMap.put("assignRoleList", assignRoleList);

        return roleMap;
    }

    /**
     * 分配角色
     * @param adminId 用户id
     * @param roleIds 分配的一个或多个角色
     */
    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {

        //删除该用户已经存在的角色
        adminRoleDao.deleteByAdminId(adminId);

        //给用户分配新的权限
        //遍历roleIds，如果roleId不为空 则给用户分配该权限
        for (Long roleId : roleIds) {
            if (!(roleId == null)){
                AdminRole adminRole = new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(roleId);
                adminRoleDao.insert(adminRole);
            }
        }
    }

}
